package com.chucang.shucang.common.security.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chucang.shucang.common.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

/**
 * @author flitsneak
 * @date 2022/9/17 9:50
 * @description mybatis-plus自动填充
 */
@Slf4j
@Component
public class BaseMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入策略
     *
     * @param metaObject 拦截对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //创建时间
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        Optional.ofNullable(SecurityUtil.getUser())
                .ifPresent(c ->
                        this.strictInsertFill(metaObject, "createdBy", String.class, c.getId().toString())
                );
        //del_flag
        this.strictInsertFill(metaObject, "delFlag", Integer.class, 0);
        this.strictInsertFill(metaObject, "status", Integer.class, 0);
    }

    /**
     * 更新策略
     *
     * @param metaObject 拦截对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //更新时间
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        Optional.ofNullable(SecurityUtil.getUser())
                .ifPresent(c ->
                        this.strictInsertFill(metaObject, "updatedBy", String.class, c.getId().toString())
                );
    }
}
